<template>  
    <div class="divPeer">
        <div class="divPage">
            <div class="divTools">
                <ul class="lstAcs">
                    <li>
                        <el-select size="small" v-model="deviceId">
                            <el-option
                            v-for="item in devices"
                            :key="item.deviceId"
                            :label="item.label"
                            :value="item.deviceId">
                            </el-option>

                        </el-select>
                    </li>
                    <li><el-button size="small" type="primary" @click="setCamera">set</el-button></li>
                    <li><el-button size="small" type="primary" @click="shareScreen">screen</el-button></li>
                </ul>
            </div>
            <div class="divVideo">
                <video autoplay id="lv"></video>
            </div>
            <ul class="lstMsg">
                <li
                    v-for="(item,index) in msgs"
                    :key="index"
                >
                    {{item}}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        mounted(){
            var me = this;
            try{
                me.$nextTick().then(_=>{
                    return me.getDevices();
                }).then(_devs=>{
                    me.devices = _devs.videoinput;
                    me.deviceId = me.devices[1].deviceId;
                    me.open();
                });
            }
            catch(er){
                console.log(er);
            }
        },
        data(){
            return{
                peer: null,
                devices:[],
                deviceId:"",
                msgs:[]
            }
        },
        methods:{
            getDevices() {
                var res = {};
                return new Promise((success, faild) => {
                    try {
                        navigator.mediaDevices.getUserMedia({video:true,audio:true}).then(function(stream) {
                            return navigator.mediaDevices.enumerateDevices();
                        }).then(function(devs) {
                            try {
                                for (var i = 0; i < devs.length; i++) {
                                    var item = devs[i];
                                    if (!res[item.kind]) {
                                        res[item.kind] = []
                                    }
                                    res[item.kind].push(item);
                                }
                            } catch (er) {
                                console.log(er);
                            }
                            success(res);
                        }).catch(function() {
                            success(res);
                        });
                    } catch (er) {
                        console.log(er);
                        success(res);
                    }
                });
            },
            open(){
                var me = this;
                try{
                    var video = document.getElementById('lv');
                    var peerOpts ={
                        configuration: {
                            "iceServers": [{
                                    //urls: "stun:39.171.53.53:3478"
                                    urls: "stun:39.171.39.247:3478"
                                        //urls: "stun:223.68.161.139:3478"
                                        //urls: "stun:223.112.194.253:40016"
                                },
                                {
                                    //urls: ["turn:39.171.53.53:3478"],
                                    urls: ["turn:39.171.39.247:3478"],
                                    //urls: ["turn:223.68.161.139:3478"],
                                    //urls: ["turn:223.112.194.253:40016"],
                                    username: "kurento",
                                    credential: "kurento"
                                }
                            ]
                        },
                        mediaConstraints: {
                            audio: true,
                            video: {
                                width: { min: 1280, ideal: 1920, max: 1920 },
                                height: { min: 720, ideal: 1080, max: 1080 }
                            },
                        },
                        localVideo:video
                    };
                    if ( me.deviceId && me.deviceId != "") {
                        peerOpts.mediaConstraints.video.deviceId = me.deviceId;
                    }  
                    var wrPeer = kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(peerOpts, function(erP) {
                        console.log(erP);
                        wrPeer.peerOption = JSON.parse(JSON.stringify(peerOpts));
                        me.peer = wrPeer;
                    });

                }
                catch(er){
                    console.log(er);
                }
            },
            setCamera(){
                var me = this;
                try{  
                    console.log(me.peer);
                    me.msgs=[];
                    //var deviceId = me.peer.localVideo.srcObject;
                    var peer = me.peer;
                    var currentDeviceId = peer.getLocalStream().getVideoTracks()[0].getSettings().deviceId;
                    var newDeviceId = me.deviceId;
                    me.msgs.push('old deviceId:'+currentDeviceId);
                    me.msgs.push('new deviceId:'+newDeviceId);
                    console.log(me.peer);

                    if( currentDeviceId!=newDeviceId){
                        me.msgs.push('stop stream tracks....');
                        var stream = peer.getLocalStream();
                        stream.getTracks().forEach( t=>{                            
                            t.stop();
                            me.msgs.push('stop stream track:'+t.label+","+t.kind);
                        });
                    }
                    var mediaConstraints= peer.peerOption.mediaConstraints;
                    mediaConstraints.video.deviceId = newDeviceId;
                    me.msgs.push(newDeviceId);
                    navigator.mediaDevices.getUserMedia(mediaConstraints).then(function(stream) {
                        try { 
                            me.msgs.push('get stream ...');
                            peer.localVideo.srcObject = stream;

                            me.msgs.push(JSON.stringify(newDeviceId));

                            var streamTracks={};
                            stream.getTracks().forEach(st=>{
                                streamTracks[st.kind] = st;
                                me.msgs.push(JSON.stringify(st.label));
                            })
                            
                            //var peerConnection = peer.peerConnection ;
                            //peerConnection.removeStream(peerConnection.getLocalStreams()[0]);
                            //+peerConnection.addLocalStream(stream);
                            peer.peerConnection.getSenders().forEach( _sender=>{
                                console.log(_sender); 
                                var kind = _sender.track.kind;
                                _sender.track.stop();
                                var stTrack = streamTracks[kind];
                                _sender.replaceTrack(stTrack);
                                me.msgs.push('sender:'+ kind +","+ stTrack.label);
                            });
                            
                        } catch (eSet) {
                            alert('1'+JSON.stringify(eSet));
                            console.log(eSet);
                        }
                    }).catch(function(erSet) {
                        alert('2'+JSON.stringify(erSet));
                        console.log(erSet);
                    });

                }
                catch(er){
                    console.log(er);
                }
            },
            shareScreen(){
                var me = this;
                try{   
                    var peer = me.peer;
                    var width;
                    var height;

                    var wWidth = width && width > 0 ? width : (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
                    var wHeight = height && height > 0 ? height : (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
                    var screenConstraints = { video: { width: { max: wWidth }, height: { max: wHeight } }, audio: true };
                    var sender = null;
                    if (navigator.mediaDevices.getDisplayMedia) {
                        navigator.mediaDevices.getDisplayMedia(screenConstraints).then(
                            function(stream) {
                                let videoTrack = stream.getVideoTracks()[0];
                                peer.localVideo.srcObject = stream;
                                sender = peer.peerConnection.getSenders().find(function(s) {
                                    return s.track.kind == videoTrack.kind;
                                });
                                sender.track.stop();
                                sender.replaceTrack(videoTrack); 
                            }
                        )
                    } else { 
                        ;
                    }

                }
                catch(er){
                    console.log(er);
                }
            },
        }
    }
</script>

<style lang="less" scoped>
    .divPeer{
        height: 100%;

        .divPage{
            width: 60%;
            margin: 10px 20%;
            .divTools{
                padding: 10px;
                ul.lstAcs{
                    list-style: none;
                    padding: 0;
                    margin: 0;
                    display: flex;
                    align-items: center;
                    li{
                        padding: 0 10px;
                    }
                }
            }

            .divVideo{
                video{
                    width: 100%;
                }
            }
        }

        ul.lstMsg{
            list-style: none;
            padding: 0;
            text-align: left;
        }
    }
</style>